<template>
  <view class="operateCom">
    <view class="list">
      <view @tap="uploadImage('album')">
        <view>
          <image src="@/static/image/34.png" mode="widthFix" />
        </view>
        <view>照片</view>
      </view>
      <view @tap="uploadImage('camera')">
        <view>
          <image src="@/static/image/35.png" mode="widthFix" />
        </view>
        <view>拍照</view>
      </view>
      <view @tap="uploadImage('video')">
        <view>
          <image src="@/static/image/36.png" mode="widthFix" />
        </view>
        <view>视频</view>
      </view>
      <view @tap="file.toClick" id="inputbox">
        <view>
          <image src="@/static/image/39.png" mode="widthFix" />
        </view>
        <view>文件</view>
      </view>
      <view
        @tap="
          goTo(
            '/pages/red/sendRed?chatId=' +
              chatId +
              '&isGroupChat=' +
              isGroupChat
          )
        "
      >
        <view>
          <image src="@/static/image/37.png" mode="widthFix" />
        </view>
        <view>红包</view>
      </view>

      <view @tap="handleCall(2, chatnfo,1)" v-if="!isGroupChat">
        <view>
          <image src="@/static/image/91.png" mode="widthFix" />
        </view>
        <view>视频通话</view>
      </view>
      <view @tap="handleCall(1, chatnfo,1)" v-if="!isGroupChat">
        <view>
          <image src="@/static/image/92.png" mode="widthFix" />
        </view>
        <view>语音通话</view>
      </view>
    </view>
  </view>
</template>

<script lang="ts">
import {
  UploadTokenApi,
  handleFileUploadForH5,
  handleFileUploadForApp,
} from "@/api/SystemApi";
import { getImageDimensions } from "@/static/ts/common";

export default {
  props: ["chatId", "isGroupChat", "chatnfo"],
  data() {
    return {
      uploadFilesTime: null as any,
    };
  },
  methods: {
    loadingFn() {
      let i: number = 0;
      let lastUpdateTime = Date.now(); // 记录上次更新时间
      uni.showLoading({
        title: `0%`,
        mask: true,
      });
      this.uploadFilesTime = setInterval(() => {
        i += 3;
        const currentTime = Date.now();
        if (currentTime - lastUpdateTime >= 500) {
          lastUpdateTime = currentTime;
          uni.showLoading({
            title: `${Math.min(i, 99)}%`,
            mask: true,
          });
        }
        if (i >= 100) {
          clearInterval(this.uploadFilesTime);
          uni.showLoading({
            title: "99%",
            mask: true,
          });
        }
      }, 500);
    },
    async uploadImage(type: string) {
      const chooseFile = type === "video" ? uni.chooseVideo : uni.chooseImage;

      chooseFile({
        count: 9,
        sourceType: [type],
        success: async (res: any) => {
          console.log(res);
          let file_suffix: any = "";
          /*#ifdef APP-PLUS*/
          file_suffix =
            type === "video" ? res.tempFilePath : res.tempFilePaths[0];
          /*#endif*/
          /*#ifdef H5*/
          file_suffix = type === "video" ? res.name : res.tempFiles[0].name;
          /*#endif*/
          file_suffix = file_suffix.split(".").pop();
          let tempFiles: any = [];
          if (type === "video") {
            tempFiles = [
              {
                path: res.tempFilePath,
                size: res.size,
                fileSuffix: file_suffix,
              },
            ];
          } else {
            tempFiles = res.tempFiles.map((file: any) => ({
              path: file.path,
              size: file.size,
              file_suffix: file_suffix,
            }));
          }

          try {
            this.loadingFn();
            for (let index = 0; index < tempFiles.length; index++) {
              let obj = await UploadTokenApi({
                file_suffix,
                file_purpose: 2,
              });
              const file = tempFiles[index];
              obj = {
                ...obj,
                uploadUrl: atob(obj.uploadurl),
                message_type: type == "video" ? 3 : 2,
                path: file.path,
                duration: res.duration,
              };
              try {
                /*#ifdef APP-PLUS*/
                await handleFileUploadForApp(file, obj);
                /*#endif*/
                /*#ifdef H5*/
                await handleFileUploadForH5(file, obj);
                /*#endif*/
                console.log(`第 ${index + 1} 个文件上传成功:`, obj);
                let sizeObj = {};
                if (type === "video") {
                  sizeObj = await getImageDimensions(
                    obj.downloadurl.replace(".mp4", ".jpg")
                  );
                } else {
                  sizeObj = await getImageDimensions(file.path);
                }

                obj = {
                  ...obj,
                  ...sizeObj,
                };

                this.getOperate(obj);
              } catch (error) {
                console.error(`第 ${index + 1} 个文件上传失败:`, file, error);
              }
            }
            clearInterval(this.uploadFilesTime);
            uni.hideLoading();
          } catch (error) {
            clearInterval(this.uploadFilesTime);
            uni.hideLoading();
            console.error("上传失败:", error);
            uni.showToast({ title: "上传失败" });
          }
        },
        fail: (err) => {
          clearInterval(this.uploadFilesTime);
          uni.hideLoading();
        },
      });
    },

    async getFile(val: string) {
      let res = JSON.parse(val);
      try {
        this.loadingFn();
        let obj = await UploadTokenApi({
          file_suffix: res.file_suffix,
          file_purpose: 2,
        });
        obj = {
          ...obj,
          ...res,
          message_type: 5,
          uploadUrl: atob(obj.uploadurl),
        };

        /*#ifdef APP-PLUS*/
        await handleFileUploadForApp({ path: res.fileURL }, obj);
        /*#endif*/
        /*#ifdef H5*/
        await handleFileUploadForH5({ path: res.fileURL }, obj);
        /*#endif*/

        console.log(obj, 123);
        clearInterval(this.uploadFilesTime);
        uni.hideLoading();
        this.getOperate(obj);
      } catch (error) {
        clearInterval(this.uploadFilesTime);
        uni.hideLoading();
      }
    },
    getOperate(item: any) {
      this.$emit("update:operateValue", item);
    },
  },
};
</script>

<script lang="renderjs" module="file">
export default {
  data() {
    return {};
  },
  methods: {
    toClick(val) {
      if (!val) return;

      let ownerInstance = this.$ownerInstance;
      const inputFile = document.createElement('input');
      inputFile.type = 'file';
      inputFile.style.display = 'none'; // 隐藏 input 元素
      inputFile.addEventListener('change', (event) => {
        const file = event.target.files[0];
        let obj={
          file_name:file.name,
            size:file.size,
            file_suffix:file.name.split(".").pop(),

          }
        if (file) {
          // 判断是否是 App 环境
          if (typeof plus !== 'undefined') {
            // App 环境处理
            const reader = new FileReader();
            reader.onload = (e) => {
              const arrayBuffer = e.target.result;
              if (arrayBuffer) {
                const blob = new Blob([arrayBuffer], { type: file.type });
                const fileName = file.name;
                const filePath = `_doc/${fileName}`;
                const reader2 = new FileReader();
                reader2.onloadend = function () {
                  const base64Data = reader2.result;
                  obj['fileURL']=base64Data
                  ownerInstance.callMethod('getFile',  JSON.stringify(obj));
                };
                reader2.readAsDataURL(blob);
              }
            };
            reader.readAsArrayBuffer(file);
          } else {
            // H5 环境处理
            const fileURL = URL.createObjectURL(file);
             obj['fileURL']=fileURL
            ownerInstance.callMethod('getFile', JSON.stringify(obj));
          }
        }
      });

      document.body.appendChild(inputFile); // 添加到 DOM 中
      inputFile.click(); // 触发文件选择
    },
  },
};
</script>
<style scoped lang="scss">
@import "../../../static/scss/chat.scss";
</style>
